import React from 'react'
import { changeNav } from '../../../actions'
import { wxGetSubProduct, wxzhctProductConf } from '../../../actions/smartDr.js'
import { connect } from 'react-redux'
import {
    Button, List, InputItem, Flex
    , WingBlank, WhiteSpace, Popup, Tag, Toast, Icon
} from 'antd-mobile'
import CSSModules from 'react-css-modules'
import hhistory from '../../../history'
import { ajaxGet, ajaxPost } from 'wxAjaxUtil';

const Item = List.Item;
const Brief = Item.Brief;
let productCode = "100027";
let subProducts = {};
let subFee = 0;
let oldJtCode = '';

var cartData = {
    "productCode": productCode,
    "sellType": "",
    "sellNum": "2",
    "flag": 1,  //1开通  2续费
    "groupConfig": {},
    "storeConfig": [],
    "productConfigLabel": "子业务",
    "productConfig": [],
    "purchaseDurationLabel": "购买时长",
    "purchaseDuration": 1,
    "serviceFeeLabel": "服务费（每门店每年）",
    "serviceFee": "0",
    "activationFeeLabel": "开通费（每店）",
    "activationFee": "0",
    "payableFee": "0",
    "remark": ""
};

var cartData2 = { "productCode": "100009", "sellType": 2, "sellNum": 1, "flag": 1, "groupConfig": { "groupCode": "G000131", "groupName": "魏琴测试集团" }, "storeConfig": [{ "storeCode": "T000781", "storeName": "魏琴测试门店" }], "productConfigLabel": "子业务", "productConfig": [{ "label": "享付", "code": "100008", "value": "0.00" }], "purchaseDurationLabel": "购买时长", "purchaseDuration": 1, "serviceFeeLabel": "服务费（每门店每年）", "serviceFee": "0.00", "activationFeeLabel": "开通费（每店）", "activationFee": "0.00", "payableFee": "0.00" }

class OpenSmartdr extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubProduct = this.handleSubProduct.bind(this);
        this.putIntoCart = this.putIntoCart.bind(this);
        this.openNow = this.openNow.bind(this);
        this.selectmd = this.selectmd.bind(this);
        this.selectjt = this.selectjt.bind(this);

        this.state = { btnDisabled: false, note: '',subFee:0 };
    }

    componentDidMount() {
        this.props.tochangeNav({
            title: "开通智慧餐厅", rbtn: [
                <Button key="1" type="primary" inline size="small">购0</Button>
            ]
        });
        this.props.wxGetSubProduct(productCode);
    }

    //子组件向父组件传值
    handleSubProduct(subp) {
        this.props.wxzhctProductConf(subp);
    }


    //选择门店
    selectmd() {
        if (Object.keys(this.props.jtData).length === 0) {
            Toast.fail('请先去添加集团！', 1);
        } else {
            oldJtCode = this.props.jtData.code;
            hhistory.push({ pathname: '/SelectDr', state: { backRouter: '/openMT' } })
        }
    }

    //选择集团
    selectjt() {
        hhistory.push({ pathname: '/SelectGroup', state: { backRouter: '/openMT' } })
    }
    madewxmtstoreinfo() {
        let wxmtstoreinfo = this.props.wxmtstoreinfo;
        let listvalue = Object.values(wxmtstoreinfo);
        let listkey = Object.keys(wxmtstoreinfo);
        let listObj = {};
        console.log(listkey,listvalue)
        for(let i = 0; i < listvalue.length;i = i+2) {
            let key = listkey[i].substring(0, listkey[i].indexOf('$'))
            listObj[key] = [{
                code: 'meituan_account', label: '美团商家账号', value: listvalue[i]
            }, {
                code: 'meituan_password', label: '美团商家密码', value: listvalue[i + 1]
            }]
        }
        return listObj
    }
    btnClick(url, type) {
        let wxmtstoreinfo = this.madewxmtstoreinfo();
        let mdData = this.props.mdData;
        let NewmdData = [];
        cartData.payableFee = (+cartData.activationFee+(+cartData.serviceFee))*mdData.length
        this.setState({
            subFee:cartData.payableFee
        })
        mdData.forEach(val =>{
            let obj = {
                storeCode:val.code,
                storeName:val.name,
                cityCode:val.cityCode,
                otherInfo:wxmtstoreinfo[val.code]
            }
            if(obj.otherInfo) {
                Toast.fail('请填写完整信息')
                return;
            }
            NewmdData.push(obj)
        })
        cartData.storeConfig = NewmdData;
        if (Object.keys(cartData.groupConfig).length === 0) {
            Toast.fail('请先去添加集团！', 1);
            return false;
        }
        if (cartData.storeConfig.length <= 0) {
            Toast.fail('请先去添加门店！', 1);
            return false;
        }
        this.setState({ btnDisabled: true }); //将按钮变为不可用
        cartData.remark = this.state.note;   //获取备注信息
        console.log(cartData);

        //发送ajax请求
        if (type == 0) {
            ajaxPost(url, cartData).then(res => {
                if (res.code && res.code == "0") {
                    Toast.success('开通申请已提交', 1);
                } else {
                    Toast.fail('开通失败', 1);
                    this.setState({ btnDisabled: false });
                }
            })
        }
        if (type == 1) {
            ajaxPost(url, cartData).then(res => {
                if (res.code && res.code == "0") {
                    Toast.success('已加入购物车', 1);
                } else {
                    Toast.fail('加入购物车失败', 1);
                    this.setState({ btnDisabled: false });
                }
            })
        }
    }

    //立即开通
    openNow() {
        this.btnClick('app/product/open', 0);
    }

    //添加购物车
    putIntoCart() {
        this.btnClick('app/shopping/cart', 1);
    }

    render() {
        const { wxSubProducts, jtData, mdData,wxmtstoreinfo} = this.props;
        subProducts = wxSubProducts;
        if (subProducts.hasOwnProperty('pricingScheme') && wxSubProducts.pricingScheme && wxSubProducts.pricingScheme.length > 0) {
            cartData.sellType = wxSubProducts.pricingScheme[0].sellType;
            cartData.serviceFee = wxSubProducts.pricingScheme[0].serviceFee;
            cartData.activationFee = wxSubProducts.pricingScheme[0].activationFee;
            cartData.purchaseDuration = wxSubProducts.pricingScheme[0].serviceDuration;
        }

        //给cartData添加集团和门店信息
        if (Object.keys(jtData).length != 0) {
            cartData.groupConfig.groupCode = jtData.code;
            cartData.groupConfig.groupName = jtData.name;
        }

        if (mdData.length && mdData.length > 0) {
        }
        let storeItems = (oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '' : mdData.map((item, index) => {
            return <Item key={item.code} thumb={item.logo} multipleLine>
                {item.name}<Brief>{item.code}</Brief>
            </Item>
        });
        console.log(cartData,wxSubProducts);
        return (
            <div>
                <List renderHeader={() => '选择开通商户'} className="my-list" styleName="bgwhite">
                    <Item extra="选择" arrow="horizontal" onClick={this.selectjt}>
                        {(jtData == null || Object.keys(jtData).length === 0) ? '请选择集团' : <span><img src={jtData.logo} />{jtData.name}</span>}
                    </Item>
                    <Item extra="选择" arrow="horizontal" onClick={this.selectmd}>
                        共<span styleName="red">{(oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '0' : mdData.length}</span>个门店
                    </Item>
                    {storeItems}
                    <Item extra="选择" style={{display:storeItems?'block':'none'}} arrow="horizontal" onClick={ () => {hhistory.push('/wxmtSetInfo')}}>
                        {'门店配置'}
                    </Item>
                </List>
                <WhiteSpace size='md' styleName="yellow" />
                <List>
                    <InputItem placeholder="备注信息选填" onBlur={value => { this.state.note = value }} />
                </List>
                <WhiteSpace size='md' styleName="yellow" />
                <List>
                    <Item>
                        <div>应付款总计 <span styleName="red">&yen;{Number(this.state.subFee).toFixed(2)}</span></div>
                    </Item>
                    <WhiteSpace size="lg" />
                    <WingBlank size="lg">
                        <Flex>
                            <Flex.Item>
                                <Button type="ghost" disabled={this.state.btnDisabled} onClick={this.putIntoCart}>加入购物车</Button>
                            </Flex.Item>
                            <Flex.Item>
                                <Button type="primary" disabled={this.state.btnDisabled} onClick={this.openNow}>立即开通</Button>
                            </Flex.Item>
                        </Flex>
                    </WingBlank>
                    <WhiteSpace size="lg" />
                </List>
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    wxSubProducts: state.wxSmartdrs.wxSubProducts,
    wxzhctSubProduct: state.wxSmartdrs.wxzhctSubProduct,
    jtData: state.wxSmartdrs.jtData,
    mdData: state.wxSmartdrs.mdData,
    wxmtstoreinfo:state.wxmtstoreinfo
})
const mapDispatchToProps = (dispatch) => ({
    tochangeNav: navogj => dispatch(changeNav(navogj)),
    wxGetSubProduct: productCode => dispatch(wxGetSubProduct(productCode)),
    wxzhctProductConf: productConfig => dispatch(wxzhctProductConf(productConfig))
})

export default connect(mapStateToProps, mapDispatchToProps)(OpenSmartdr)